<template>
  <div id="chatbox" v-if="!dataLoading">
    <div class="chatbox" @drop.prevent="dropImage" :class="{opensidebar: data.sidebar}">
      <div class="top">
        <div class="name">
          {{data.user.name ? data.user.name : data.user.nickname}}<span>上次沟通<Time :interval="1" :time="data.user.last_butt_time || 0" /> </span>
        </div>
      </div>
      <div class="chat">
        <Split v-model="split2" min="100px" mode="vertical" >
          <div slot="top" class="demo-split-pane">
            <div class="chat_list">
              <vue-scroll v-viewer @handle-resize="handleResize" ref="msg_list" :ops="msg_list.ops" class="msg_list_box">
                <center><a @click="getChatLog"><font color="#2c90ff">查看更多消息</font></a></center>
                <msgItem :isshow="((parseInt(item.cs_id) === parseInt(data.csuser.id)) || (parseInt(item.pid) === parseInt(data.csuser.id))) && item.openid === data.user.openid" ref="msg_item" v-for="(item, index) in data.chatlog" :key="index" :data="item" :user="data.user" :csuser="data.csuser"></msgItem>
                <!-- <msgItem v-if="((parseInt(item.cs_id) === parseInt(data.csuser.id)) || (parseInt(item.pid) === parseInt(data.csuser.id))) && item.openid === data.user.openid" ref="msg_item" v-for="(item, index) in data.chatlog" :key="index" :data="item" :user="data.user" :csuser="data.csuser"></msgItem> -->
                <div class="__bottom__" style="height:1px;"><!-- 列表最底部的定位 --></div>
              </vue-scroll>
            </div>
          </div> 
          <div slot="bottom" class="demo-split-pane">
              <div class="toolsbar">
                <div class="left">
                  <Poptip placement="top-start">
                    <Tooltip :transfer="true" placement="top" content="表情">
                    <div class="item"><Icons name="xiaolian" /></div>
                    </Tooltip>
                    <div slot="content" class="facelist">
                      <div class="img" v-for="(item, index) in face.list" :key="index">
                        <img :src="item.url" @click="addFace(index)">
                        <!--  @click="addFace(index)" -->
                      </div>
                    </div>
                  </Poptip>
                  <Tooltip :transfer="true" placement="top" content="图片">
                  <div class="item" @click="upLoadPic"><Icons name="tupian" /></div>
                  </Tooltip>
                </div>
              </div>
              <editor style="height:calc(100% - 65px);" @sendTextMsg="sendTextMsg" ref="inputbox"/>
              <div class="btn_list">
                <span>Shift + Enter 换行</span>
                <button class="send" @click="sendText">发送</button>
              </div>
          </div>
        </Split>
      </div>
      <div class="opensidebar" :class="{active: data.sidebar}" @click="changeSidebar">
        <Icons name="you"/>
      </div>
    </div>
    <div class="userinfo" :class="{opensidebar: data.sidebar}">
      <div class="top">
        <div class="item" @click="userinfo.index = 1" :class="{active: userinfo.index == 1}"><div class="icon"><Icons name="jilu" /></div><span>常用回复</span></div>
        <div class="item" @click="userinfo.index = 2" :class="{active: userinfo.index == 2}"><div class="icon"><Icons name="yonghutouxiang" /></div><span>用户标记</span></div>
      </div>
      <div class="contbox used_reply" :class="{active: userinfo.index == 1}">
        <Collapse simple :value="customReply.length > 0 ? '2' : '1'">
          <Panel name="1">
            通用回复
            <div slot="content">
              <div class="reply_item" v-for="(item, index) in genReply" :key="index" @click="sendQuickReply(item)">
                <Tooltip :transfer="true" placement="left" max-width="200" :content="item">
                  <div class="text">
                    <p>{{item}}</p>
                  </div>
                </Tooltip>
              </div>
            </div>
          </Panel>
          <Panel name="2">
            自定义回复
            <div slot="content">
              <div class="reply_item" v-for="(item, index) in customReply" 
                    v-dragging="{ item: item, list: customReply, group: 'quick_reply' }" :key="index" 
                    @click="sendQuickReply(item)">
                <Tooltip :transfer="true" placement="left" max-width="200" :content="item">
                  <div class="text">
                    <p>{{item}}</p>
                    <div class="opt">
                      <Icons @click.native.stop="delReply(index)" name="chenghao"/>
                      <Icons @click.native.stop="editReply(index)" name="edit"/>
                    </div>
                  </div>
                </Tooltip>
              </div>
              <div class="add" @click="setReplyshow = true">
                <Icon type="md-add" />添加一个快捷回复
              </div>
              <Modal v-model="setReplyshow" title="设置自定义常用回复" @on-ok="addCustomReply" >
                <Input v-model="setReplyText" type="textarea" :autosize="{minRows: 2,maxRows: 5}" placeholder="Enter something..." />
              </Modal>
            </div>
          </Panel>
        </Collapse>
      </div>
      <div class="contbox user_info" :class="{active: userinfo.index == 2}">
        <div class="heade">
          <img :src="data.user.headimgurl || defaultpic" alt="" class="headpic">
        </div>
        <div class="name">
          {{data.user.nickname}}<span v-if="data.user.name">({{data.user.name}})</span>
          <b class="sex" type="1" v-if="data.user.sex === 1"><Icon   type="md-male" /></b>
          <b class="sex" type="2" v-else-if="data.user.sex === 2"><Icon type="md-female" /></b>
        </div>
        <div class="info">
          <p>{{data.csuser.wxname}}</p>
          <p>通过{{subscribe_scene[data.user.subscribe_scene] || '未知渠道'}}关注</p>
          <p>{{data.user.country + data.user.province + data.user.city}}</p>
        </div>
        <div class="tags">
          <div class="tit" v-if="data.user.tagid_list && data.csuser.tags_list">
            <b>现有标签({{Object.keys(data.user.tagid_list).length}})</b>
            <span @click="userinfo.setTags = true">添加标签<Icon type="ios-create-outline" /></span>
          </div>
          <Modal width="480px" class-name="all_chatlog" v-model="userinfo.setTags" :title="'设置用户标签'">
            <div class="tags_list">
              <div class="top" text="用户当前的标签">
                <Alert type="warning" v-show="Object.keys(data.user.tagid_list).length == 0">当前用户还没有标签，快去添加吧！</Alert>
                <userTags ref="user_tags" @updataTagStatus="updataTagStatus" class="tags" v-for="(item, index, num) in data.user.tagid_list" :key="num" :user="data.user" :csuser="data.csuser" :tagid="item" />
              </div>
              <div class="hr"><span>全部标签</span></div>
              <div class="allbox">
                <div class="group" v-for="(item, index) in data.csuser.tags_list.group" :key="index">
                  <div class="tit">{{item.name}}</div>
                  <userTags ref="user_tags" @updataTagStatus="updataTagStatus"  class="item" v-for="(item1, index1, num) in item.s_label" :key="num" :user="data.user" :csuser="data.csuser" :tagid="item1.group_id" />
                  <Alert type="warning" v-show="item.s_label.length == 0">当前没有还没有内容，请等待管理员添加。</Alert>
                </div>
              </div>
            </div>
          </Modal>
          <div class="list" :class="{active: userinfo.tags_show}" v-if="data.user.tagid_list && data.csuser.tags_list">
            <div :style="'border:1px solid '+ (data.csuser.tags_list.list[item].color) +';'" class="item" v-for="(item, index, num) in data.user.tagid_list" :key="num">
              <b :style="'background:'+ (data.csuser.tags_list.list[item].color) +';'">{{parseInt(index) + 1}}</b>
              <span :style="'color:'+ (data.csuser.tags_list.list[item].color) +';'">{{data.csuser.tags_list.list[item].name}}</span>
            </div>
            <div class="more" :class="{active: userinfo.tags_show}">
              <Icons title="展开" @click.native="userinfo.tags_show = !userinfo.tags_show" name="xia-copy" />
            </div>
          </div>
        </div>
        <div class="extra" ref="extra_info">
            <div class="tit">备注信息</div>
            <div class="input">
              <span>名 字:</span>
              <input name="name" @blur="setExtraInfo" :value="data.user.name" type="text" >
            </div>
            <div class="input" v-show="false">
              <span>电 话:</span>
              <input name="phone" @blur="setExtraInfo" :value="data.user.phone" type="text" >
            </div>
            <div class="input">
              <span>微 信:</span>
              <input name="wechat_num" @blur="setExtraInfo" :value="data.user.wechat_num" type="text" >
            </div>
            <div class="input" v-show="false">
              <span>年 龄:</span>
              <input name="age" @blur="setExtraInfo" :value="data.user.age" type="number" >
            </div>
            <div class="input">
              <span>备 注:</span>
              <textarea name="remark" @blur="setExtraInfo" :value="data.user.remark" rows="3" />
            </div>
          </div>
      </div>
    </div>
  </div>
</template>

<script>
  import facelist from '../../assets/data/face.json'
  // import methods from './methods.js'
  import msgItem from '../msgItem'
  import editor from '../editor'
  import userTags from '../userTags'
  import Tips from '../../assets/js/tips.js'

  export default {
    name: 'chatBox',
    data: () => {
      return {
        edit_reply: null,
        setReplyshow: false,
        setReplyText: '',
        dataLoading: false,
        genReply: [],
        customReply: [],
        defaultpic: require('../../assets/images/timg.jpg'),
        split2: 0.7,
        face: {
          list: facelist
        },
        subscribe_scene: {
          'ADD_SCENE_SEARCH': '公众号搜索',
          'ADD_SCENE_ACCOUNT_MIGRATION': '公众号搜索',
          'ADD_SCENE_PROFILE_CARD': '公众号搜索',
          'ADD_SCENE_QR_CODE': '扫描二维码',
          'ADD_SCENEPROFILE LINK': '图文页内名称点击',
          'ADD_SCENE_PROFILE_ITEM': '图文页右上角菜单',
          'ADD_SCENE_PAID': '支付后关注',
          'ADD_SCENE_OTHERS': '其他'
        },
        userinfo: {
          index: 1,
          quick_reply: [
            '您好，在吗？',
            '您好，请问你想解决什么肌肤问题呢？',
            '您好，我是郑明明专业护肤团队的资深客服，你是想解决皮肤皱纹的问题吗？',
            '您好，请问你也是本人需要调理肌肤皱纹情况吗？',
            '您好，这是是郑明明团队人工客服，有什么能够帮助到你的呢？',
            '您好, 我是吉米团队人工客服,有什么可能为您效劳的?'
          ],
          tags_show: false,
          setTags: false
        },
        msg_list: {
          ops: {
            vuescroll: {
              mode: 'native'
            },
            scrollPanel: {
              initialScrollY: '100%',
              speed: 10
            },
            rail: {
              size: '3px',
              gutterOfSide: '0px'
            },
            bar: {
              background: '#3e58c9',
              opacity: 0.6
            }
          }
        },
        data: {
          sidebar: true,
          user: {},
          csuser: {},
          chatlog: []
        }
      }
    },
    components: {
      msgItem,
      editor,
      userTags
    },
    props: {
      user: {
        default: {}
      },
      csId: {
        default: {}
      }
    },
    watch: {
      user () {
        this.loadUserInfo()
      },
      csId () {
        this.loadUserInfo()
      },
      async customReply () {
        await this.$fn.setCustomReply(this.csId, this.customReply)
      }
    },
    created () {
      window.$chatWin = this
      this.loadUserInfo()
    },
    methods: {
      changeSidebar () {
        this.data.sidebar = !this.data.sidebar
        let isMaximized = this.$electron.remote.getCurrentWindow().isMaximized()
        if (!isMaximized) {
          let winsize = this.$electron.remote.getCurrentWindow().getBounds()
          if (this.data.sidebar) {
            winsize.width += 200
          } else {
            winsize.width -= 200
          }
          winsize.width = winsize.width > 580 ? winsize.width : 580
          this.$electron.remote.getCurrentWindow().setBounds(winsize)
        }
      },
      async delReply (index) {
        this.customReply.splice(index, 1)
        await this.$fn.setCustomReply(this.csId, this.customReply)
        this.$forceUpdate()
      },
      editReply (index) {
        this.setReplyshow = true
        this.setReplyText = this.customReply[index]
        this.edit_reply = index
      },
      openSidebar () {
        this.data.sidebar = !this.data.sidebar
        this.$forceUpdate()
      },
      // 加载用户资源
      async loadUserInfo () {
        try {
          // 1.获取用户信息
          this.data = {
            sidebar: this.data.sidebar
          }
          this.dataLoading = true
          this.$forceUpdate()
          var user = await this.$fn.getSqlUser(this.user.openid)
          this.data.user = user
          this.$forceUpdate()
          // 2.获取客服信息
          var csuser = await this.$fn.getCuUser(this.csId)
          if (csuser.status !== 1) throw new Error('获取客服信息失败')
          this.data.csuser = csuser.cs_info
          this.$forceUpdate()
          // 3.获取标签列表
          var allTags = await this.$fn.getAllTags(csuser.cs_info.auid)
          this.data.csuser.tags_list = allTags
          // 4.获取聊天记录
          var locaChatlog = await this.$db.chatlog_list.getChatlog(user.openid)
          var chatlog
          if (locaChatlog.length > 0) {
            chatlog = locaChatlog
          } else {
            chatlog = await this.$fn.getChatLog({
              cs_id: this.csId,
              openid: this.user.openid,
              last_time: parseInt(Date.now() / 1000)
            })
          }
          // 5.回去通用常用回复
          var genReply = await this.$fn.getUsual(csuser.cs_info.auid)
          this.genReply = genReply
          // 6.获取自定义常用回复
          var customReply = await this.$fn.getCustomReply(this.csId)
          this.customReply = customReply
          this.data.chatlog = chatlog
          this.dataLoading = false
          this.$forceUpdate()
        } catch (e) {
          this.dataLoading = false
        }
        this.$listeners['load-done']()
      },
      // 刷新消息列表滚动条
      handleResize () {
        this.$refs['msg_list'].refresh()
        this.$refs['msg_list'].scrollTo({
          y: '100%'
        })
      },
      // 上传图片
      upLoadPic () {
        let input = document.createElement('input')
        input.setAttribute('type', 'file')
        var _this = this
        input.onchange = function () {
          _this.getMediaId(this.files[0])
        }
        input.click()
      },
      // 获取图片的tMediaId
      async getMediaId (file) {
        this.$Message.loading({
          content: '上传中',
          uration: 0
        })
        try {
          let datas = {
            appid: this.data.csuser.appid,
            type: 'image',
            file: file
          }
          let result = await this.$fn.getMediaId(datas)
          this.$Message.destroy()
          if (result.status === 1) {
            let html = `<img class="pictrue" path="${result.path}" src="${this.$store.state.Config.web_url + result.path}" mediaId="${result.media_id}" />`
            this.$refs['inputbox'].insertHTML(html)
          } else {
            throw new Error('上传失败')
          }
        } catch (e) {
          console.log(e)
          this.$Message.error('上传失败')
        }
      },
      // 发送文字消息
      sendText () {
        let result = this.$refs['inputbox'].getInputCont()
        this.sendTextMsg(result.text, result.html, result.img)
        this.$refs['inputbox'].clearContent()
      },
      async sendTextMsg (text, html, img) {
        img = img || []
        html = html || ''
        var src = text
        var newstr = src || ''
        newstr = newstr.replace(/^(\s|\u00A0)+/, '').replace(/(\s|\u00A0)+$/, '')
        if (newstr === '' && img.length === 0) {
          this.$Message.warning('不能发送空白消息')
          return
        }
        if (img.length > 0) {
          for (let i = 0; i < img.length; i++) {
            let _img = img[i]
            let msg = {
              appid: this.data.csuser.appid,
              content: _img.content,
              cs_id: this.data.csuser.id,
              media_id: _img.media_id,
              openid: this.data.user.openid,
              send_time: parseInt(Date.now() / 1000),
              send_type: 1002,
              type: 'image'
            }
            this.data.chatlog.push(msg)
            let index = this.data.chatlog.length - 1
            this.$forceUpdate()
            setTimeout(() => {
              this.$refs['msg_list'].scrollTo({
                y: '100%'
              })
              this.$refs['msg_list'].refresh()
            }, 0)
            try {
              var result1 = await this.$fn.sendMsgs(msg)
              if (result1.status === 1) {
                let arrs = this.data.chatlog[index]
                arrs.send_state = 1
                this.$set(this.data.chatlog, index, arrs)
                this.$forceUpdate && this.$forceUpdate()
                window.$chatBox.updataMsgUser(msg, 1)
              } else {
                throw new Error('发送失败')
              }
            } catch (e) {
              console.log(e)
              let arrs = this.data.chatlog[index]
              if (result1.status === 1) {
                arrs.send_state = 1
              } else {
                arrs.send_state = 0
              }
              this.$set(this.data.chatlog, index, arrs)
              this.$forceUpdate()
            }
          }
        }
        if (newstr === '') {
          return
        }
        var msg = {
          user_id: this.data.user.user_id,
          appid: this.data.csuser.appid,
          openid: this.data.user.openid,
          cs_id: this.data.csuser.id,
          type: 'text',
          content: src,
          send_type: 1002,
          send_time: Date.parse(new Date()) / 1000,
          send_state: 2
        }
        this.data.chatlog.push(msg)
        var index = this.data.chatlog.length - 1
        this.$forceUpdate()
        setTimeout(() => {
          this.$refs['msg_list'].scrollTo({
            y: '100%'
          })
          this.$refs['msg_list'].refresh()
        }, 0)
        try {
          var result = await this.$fn.sendMsgs(msg, this.data.user.user_id)
          if (result.status === 1) {
            var arrs = this.data.chatlog[index]
            arrs.send_state = 1
            this.$set(this.data.chatlog, index, arrs)
            this.$forceUpdate()
            this.$refs['msg_item'].forEach((item) => { item.$forceUpdate() })
            window.$chatBox.updataMsgUser(msg, 1)
          } else {
            throw new Error('发送失败')
          }
        } catch (e) {
          let arrs = this.data.chatlog[index]
          if (result.status === 1) {
            arrs.send_state = 1
            window.$chatBox.updataMsgUser(msg, 1)
          } else {
            arrs.send_state = 0
          }
          this.$set(this.data.chatlog, index, arrs)
          this.$forceUpdate()
          this.$refs['msg_item'].forEach((item) => { item.$forceUpdate() })
        }
      },
      // 添加表情到输入框
      addFace (index) {
        this.$refs['inputbox'].insertHTML('<img class="face" src="' + this.face.list[index].url + '" alt="' + this.face.list[index].value + '" />')
      },
      // 拖拽图片上传
      dropImage (e) {
        if (e.dataTransfer.files[0]) {
          var file = e.dataTransfer.files[0]
          this.getMediaId(file)
        } else {
          this.$refs['inputbox'].insertHTML(e.dataTransfer.getData('text'))
        }
      },
      // 打开离线消息窗口
      openMassbox () {
        this.$emit('openMassbox')
      },
      // 发送常用回复
      sendQuickReply (text) {
        this.sendTextMsg(text)
      },
      // 设置用户额外信息
      async setExtraInfo () {
        var el = this.$refs['extra_info']
        var data = {
          uid: this.data.user.user_id,
          name: el.querySelector('[name="name"]').value,
          phone: el.querySelector('[name="phone"]').value,
          wechat_num: el.querySelector('[name="wechat_num"]').value,
          age: el.querySelector('[name="age"]').value,
          remark: el.querySelector('[name="remark"]').value
        }
        // 0 保存
        try {
          var result = await this.$fn.setUserInfo(data)
          if (result.status !== 1) {
            throw new Error('修改失败')
          }
          this.$Message.success('修改成功')
        } catch (e) {
          this.$Message.error('修改失败')
          return
        }
        // 第一步修改当前页面的
        Object.assign(this.data.user, data)
        this.$forceUpdate()
        // 2.改变消息列表里面的(传递到父组件)
        this.$emit('setuserinfo', this.data.user)
      },
      // 向上获取消息
      async getChatLog () {
        var oldH = this.$refs['msg_list'].$refs.scrollContent.offsetHeight
        var lastTime
        if (this.data.chatlog.length === 0) {
          lastTime = parseInt(Date.now() / 1000)
        } else {
          lastTime = this.data.chatlog[0].send_time
        }
        try {
          var result = await this.$fn.getChatLog({
            cs_id: this.csId,
            openid: this.user.openid,
            last_time: lastTime
          })
          if (result.length === 0) {
            throw new Error('没有新消息了')
          }
          result.push(...this.data.chatlog)
          this.data.chatlog = result
          this.$forceUpdate()
          this.$refs['msg_list'].refresh()
          setTimeout(() => {
            var newH = this.$refs['msg_list'].$refs.scrollContent.offsetHeight
            if (newH === oldH) {
              this.$Message.warning('没有新消息了')
            } else {
              this.$refs['msg_list'].scrollTo({
                y: newH - oldH
              })
              this.$refs['msg_list'].refresh()
            }
          }, 10)
        } catch (e) {
          console.log(e.message)
          this.$Message.warning('没有新消息了')
        }
      },
      // 从微信后台同步用户信息
      async refreshWxUser () {
        let loadingTips = new Tips({
          msg: '正在查询微信服务器...',
          type: 'loading'
        })
        loadingTips.show()
        var result = await this.$fn.getWxUser(this.data.user.openid, this.data.csuser.appid)
        loadingTips.hide()
        if (result.status === 1) {
          // 更新当前用户
          this.data.user.nickname = result.result.nickname
          this.data.user.headimgurl = result.result.headimgurl
          // 更新消息列表用户
          var changeMsguser = null
          window.$chatBox.data[this.data.csuser.id].msguser.forEach((item) => {
            if (item.openid === this.data.user.openid) {
              item.nickname = result.result.nickname
              item.headimgurl = result.result.headimgurl
              changeMsguser = item
            }
          })
          // 更新完消息列表平，存储数据库
          if (changeMsguser) {
            await this.$db.user_list.addUser(changeMsguser)
          }
          // 更新联系人列表用户
          window.$chatBox.data[this.data.csuser.id].alluser.forEach((item) => {
            if (item.openid === this.data.user.openid) {
              item.nickname = result.result.nickname
              item.headimgurl = result.result.headimgurl
            }
          })
          // 刷新页面渲染
          this.$forceUpdate()
          window.$chatBox.$forceUpdate()
          if (window.$chatBox.$refs['msguser_list']) window.$chatBox.$refs['msguser_list'].refreshData()
          if (window.$chatBox.$refs['alluser_list']) window.$chatBox.$refs['alluser_list'].refreshData()
          this.$refs['msg_item'].forEach((item) => { item.$forceUpdate() })
          // window.$chatBox.$re
          this.$Message.success('更新成功')
        } else {
          this.$Message.error('获取微信信息失败')
        }
      },
      // 添加常用回复
      async addCustomReply () {
        if (this.edit_reply !== null) {
          let str = this.setReplyText
          this.setReplyText = ''
          let _str = str.replace(/(^\s*)|(\s*$)/g, '')
          if (_str !== '') {
            let msg = this.$Message.loading({
              content: 'Loading...',
              duration: 0
            })
            this.customReply[this.edit_reply] = str
            this.edit_reply = null
            await this.$fn.setCustomReply(this.csId, this.customReply)
            msg()
            this.$forceUpdate()
          }
          return
        }
        let str = this.setReplyText
        this.setReplyText = ''
        let _str = str.replace(/(^\s*)|(\s*$)/g, '')
        if (_str !== '') {
          let msg = this.$Message.loading({
            content: 'Loading...',
            duration: 0
          })
          this.customReply.push(str)
          await this.$fn.setCustomReply(this.csId, this.customReply)
          msg()
          this.$forceUpdate()
        }
      },
      // 刷新标签状态
      updataTagStatus () {
        this.$forceUpdate()
        this.$refs['user_tags'].forEach((item) => { item.$forceUpdate() })
      }
    }
  }
</script>

<style lang="less">
  @import './style.less';
</style>
